package vn.com.hung.notetaker.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import vn.com.hung.notetaker.datatypes.PaperRecord;
import vn.com.hung.notetaker.datatypes.PaperTags;

public class PaperDataLoader extends AbstractLoader {
    
    private List<PaperRecord> papers = new ArrayList<PaperRecord>();
    
    public PaperDataLoader(String path) {
        this.path = path;
    }
    
    @Override
    public void load() {
        try {
            File data = new File(path);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(data);
            doc.getDocumentElement().normalize();
            NodeList paperList = doc.getElementsByTagName(PaperTags.PAPER_TAG);
            for (int i = 0; i < paperList.getLength(); i++) {
                Node node = paperList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element elem = (Element) node;
                    PaperRecord paper = new PaperRecord();
                    paper.setTitle(getValue(PaperTags.TITLE_TAG, elem));
                    paper.setStatus(getValue(PaperTags.STATUS_TAG, elem));
                    paper.setAuthors(getValue(PaperTags.AUTHORS_TAG, elem));
                    paper.setLink(getValue(PaperTags.LINK_TAG, elem));
                    paper.setConference(getValue(PaperTags.CONFERENCE_TAG,elem));
                    paper.setTags(getValue(PaperTags.TAGS_TAG, elem));
                    papers.add(paper);
                    
                }
                
            }
        } catch (Exception e) {
            e.printStackTrace();
            DialogDisplayer.showDefaultErrorDialog("input is not valid");
        }
    }
    
    private String getValue(String tag, Element elem) {
        NodeList nodes = elem.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = (Node) nodes.item(0);
        return node.getNodeValue();
    }
    
    public List<PaperRecord> getPapers() {
        return papers;
    }

}
